import React, {useEffect, useState} from 'react'
import {
	Button,
	Upload,
	Row,
	Col,
	Steps,
	message,
	Modal,
	Space,
	Form,
	Select,
} from 'antd'
import styles from './index.less'
import {getTemplateUrl} from '@/service/common/download'
import CustomTable from '@/components/Table'
// 图标
import {IconFont} from '@/utils/common/tool'

const {Step} = Steps
type PropsType = {
	title?: string // 弹框标题
	isModalOpen: boolean // 弹框是否可见
	setIsModalOpen: React.Dispatch<React.SetStateAction<boolean>>
	importData: any // 导入保存方法
	onTableList: any // 获取导入失败表格数据
	getListData: any // 导入成功刷新列表数据
	uploadFileUrl?: string // 上传模板url
	fileNmae?: string
	columns: any
	supplierType: string | undefined // 选中的供应商类型
	setSupplierType: React.Dispatch<React.SetStateAction<string | undefined>>
	sourceId: number | undefined
	templateType: string // 模板类型
}

const batchUpload = (props: PropsType) => {
	const {
		title = '批量导入',
		isModalOpen,
		setIsModalOpen,
		onTableList,
		getListData,
		importData,
		uploadFileUrl,
		fileNmae = 'file',
		columns,
		supplierType,
		setSupplierType,
		sourceId,
		templateType,
	} = props
	const [current, setCurrent] = useState(0)
	const [show, setShow] = useState(true)
	const [errorList, setErrorList] = useState<any>([])
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [total, setTotal] = useState(0)
	const [successCount, setSuccessCount] = useState(0)
	const [loading, setLoading] = useState(false)
	const [uploadId, setUploadId] = useState('')
	const [form] = Form.useForm()

	// 页码变化更新导入失败表格数据
	const getData = () => {
		setLoading(true)
		onTableList({batch: uploadId, ...params})
			.then((res: any) => {
				if (res?.success) {
					setTotal(res?.data?.total)
					const newData = res?.data?.records?.map(
						(item: {temporaryData: string}) =>
							JSON.parse(item?.temporaryData),
					)
					setErrorList(newData)
					setLoading(false)
				}
			})
			.catch((error: any) => {
				message.error(error)
				setLoading(false)
			})
	}
	useEffect(() => {
		if (current === 1 || current === 2) {
			getData()
		}
	}, [params, current])

	const onCancel = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
		setShow(true)
		setCurrent(0)
		setIsModalOpen(false)
	}
	const onBack = () => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
		setShow(true)
		setCurrent(0)
		if (current === 0 || current === 2) {
			setIsModalOpen(false)
		} else {
			setCurrent(current - 1)
		}
	}

	// 批量处理提交
	const onBatchSubmit = async () => {
		if (current < 2) {
			setCurrent(current + 1)
		} else if (current === 2) {
			importData({batch: uploadId})
				.then((res: any) => {
					if (res.success) {
						onCancel()
						message.success('导入成功')
						getListData()
					}
				})
				.catch((error: any) => {
					message.error(error)
				})
		}
	}
	const uploadProps = {
		action: uploadFileUrl,
		name: fileNmae,
		beforeUpload: (file: any) => {
			const isLt200M = file.size / 1024 / 1024 < 200
			if (!isLt200M) {
				message.error('文件必须小于200MB')
			}
			return isLt200M
		},
		onChange(info: any) {
			if (info.file.status === 'done') {
				message.success('上传成功')
				setShow(false)
				setUploadId(info?.file?.response?.data?.batch)
				setSuccessCount(info?.file?.response?.data?.successCount)
			}
			if (info.file.status === 'error') {
				setShow(false)
				message.error(info?.file?.response.msg)
			}
		},
		onDrop() {},
		onRemove(info: any) {
			setShow(true)
			message.success(`${info?.name}移除成功`)
		},
	}
	return (
		<Modal
			title={title}
			open={isModalOpen}
			onCancel={onCancel}
			width="50%"
			destroyOnClose
			footer={
				<>
					<Button size="small" onClick={onBack}>
						{current === 0 ? '取消' : '上一步'}
					</Button>
					<Button
						type="primary"
						size="small"
						onClick={onBatchSubmit}
						disabled={current === 0 && show === true}>
						{current === 2 ? '保存' : '下一步'}
					</Button>
				</>
			}>
			<div className={styles.batchUpload}>
				<Row gutter={12}>
					<Col sm={{span: 22, offset: 1}}>
						<Steps current={current} labelPlacement="vertical">
							<Step title="下载模板，上传文件" />
							<Step title="文件导入，数据检测" />
							<Step title="确认结果，完成导入" />
						</Steps>
					</Col>
				</Row>
				{current >= 1 ? (
					<Row gutter={12}>
						<Col sm={{span: 24}}>
							<div className={styles.info}>
								<Space>
									<span style={{color: '@primary-color'}}>
										已成功{successCount}条
									</span>
									<span style={{color: '#FF2E30'}}>
										失败{total}条
									</span>
								</Space>
							</div>
						</Col>
						<Col sm={{span: 24}}>
							<div className="customTable">
								<CustomTable
									params={params}
									columns={columns}
									pagination
									total={total}
									callback={(pagination: any) => {
										setParams(pagination)
									}}
									loading={loading}
									dataSource={errorList}
								/>
							</div>
						</Col>
					</Row>
				) : (
					<Row gutter={12}>
						<Col sm={{span: 24}}>
							<Form
								form={form}
								name="basic"
								layout="horizontal"
								labelCol={{flex: '95px'}}
								labelAlign="right"
								labelWrap
								autoComplete="off">
								<Row gutter={12}>
									<Col span={12}>
										<Form.Item
											label="供应商类型"
											name="supplierType"
											rules={[{required: true}]}
											colon>
											<Select
												placeholder="请选择"
												onChange={(value) => {
													setSupplierType(value)
												}}
												options={[
													{
														value: 'sp渠道供应商',
														label: 'sp渠道供应商',
													},
													{
														value: '代运营资产方',
														label: '代运营资产方',
													},
													{
														value: '处置供应商',
														label: '处置供应商',
													},
													{
														value: '车司平台',
														label: '车司平台',
													},
													{
														value: '其他类型',
														label: '其他类型',
													},
												]}
											/>
										</Form.Item>
									</Col>
								</Row>
							</Form>
						</Col>

						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-xiazai" />
								</div>
								<div className="inlineText">
									<div className="inlineContent">
										<div className="text title">
											下载文件模板、填写导入信息
										</div>
										<Button
											type="primary"
											shape="round"
											size="small"
											className="downOrupload"
											onClick={() =>
												getTemplateUrl(
													sourceId,
													templateType,
												)
											}>
											下载模板
										</Button>
									</div>
								</div>
							</div>
						</Col>
						<Col sm={{span: 24}}>
							<div className="stepBox">
								<div className="inlineImg">
									<IconFont type="icon-a-shangchuan1" />
								</div>
								<div className="inlineText">
									<div className="inlineContent">
										<div className="text title">
											上传导入模板
										</div>
										<div className="text">
											支持文件xls、xlsx（即Excel表格），文件大小不得超过200M，最大支持导入50万条数据
										</div>
									</div>

									<>
										<Upload {...uploadProps}>
											{!show ? (
												''
											) : (
												<Button
													type="primary"
													shape="round"
													size="small"
													className="downOrupload"
													disabled={!supplierType}>
													上传文件
												</Button>
											)}
										</Upload>
									</>
								</div>
							</div>
						</Col>
					</Row>
				)}
			</div>
		</Modal>
	)
}
export default batchUpload
